// 完善用户信息页面
const { cleanAvatarUrl } = require("../../utils/avatar.js");

Page({
  data: {
    userInfo: null,
    loading: false,
    nickname: "",
    avatarUrl: "",
    phone: "",
    returnUrl: null, // 完善信息后要返回的页面URL
    userSettings: {
      setting1: "", // 动态标题
      setting2: "",
      setting3: "",
    },
  },

  onLoad(options) {
    // 获取用户信息
    const userInfo = wx.getStorageSync("userInfo");
    this.setData({ userInfo });

    // 加载用户设置
    this.loadUserSettings();

    // 如果已有用户信息，预填充表单
    if (userInfo) {
      // 清理头像URL
      const avatarUrl = cleanAvatarUrl(userInfo.avatar || "");

      this.setData({
        nickname: userInfo.nickname || "",
        avatarUrl: avatarUrl,
        phone: userInfo.phone || "",
      });
    }

    // 获取返回URL
    if (options.returnUrl) {
      this.setData({
        returnUrl: decodeURIComponent(options.returnUrl),
      });
    }
  },

  // 选择头像
  async onChooseAvatar(e) {
    const { avatarUrl } = e.detail;

    // 显示上传进度
    wx.showLoading({
      title: "上传头像中...",
      mask: true,
    });

    try {
      // 上传头像到服务器
      const { userApi } = require("../../utils/api.js");
      const uploadResult = await userApi.uploadAvatar(avatarUrl);

      if (uploadResult.code === 0) {
        // 构建完整的头像URL
        const fullAvatarUrl = cleanAvatarUrl(uploadResult.data.url);

        this.setData({
          avatarUrl: fullAvatarUrl,
        });

        wx.showToast({
          title: "头像上传成功",
          icon: "success",
          duration: 1500,
        });
      } else {
        throw new Error(uploadResult.message || "头像上传失败");
      }
    } catch (error) {
      wx.showToast({
        title: "头像上传失败，请重试",
        icon: "none",
        duration: 2000,
      });
    } finally {
      wx.hideLoading();
    }
  },

  onNicknameInput(e) {
    this.setData({
      nickname: e.detail.value,
    });
  },

  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value,
    });
  },

  // 获取微信用户信息
  getWechatUserInfo() {
    wx.getUserInfo({
      success: (res) => {
        this.setData({
          wechatUserInfo: res.userInfo,
          isComplete: false,
        });
      },
      fail: (error) => {
        wx.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
      },
    });
  },

  // 完善用户信息
  async completeProfile() {
    const { nickname, avatarUrl, phone, userInfo } = this.data;

    // 验证头像
    if (!avatarUrl) {
      wx.showToast({
        title: "请选择头像",
        icon: "none",
      });
      return;
    }

    if (!nickname.trim() || nickname.trim() === "微信用户") {
      wx.showToast({
        title: `请修改${this.data.userSettings.setting3}`,
        icon: "none",
      });
      return;
    }

    if (!phone || phone.trim() === "") {
      wx.showToast({
        title: `请输入${this.data.userSettings.setting2}`,
        icon: "none",
      });
      return;
    }

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      wx.showToast({
        title: `请输入正确的${this.data.userSettings.setting2}`,
        icon: "none",
      });
      return;
    }

    this.setData({ loading: true });

    try {
      const { userApi } = require("../../utils/api.js");

      // 更新用户信息
      const updateData = {
        nickname: nickname.trim(),
        avatar: avatarUrl,
        phone: phone.trim(),
      };

      const result = await userApi.updateUserInfo(updateData);

      if (result.code === 0) {
        // 更新本地存储的用户信息
        const updatedUserInfo = {
          ...userInfo,
          nickname: nickname.trim(),
          avatar: avatarUrl,
          phone: phone.trim(),
          wechat_user: {
            ...userInfo.wechat_user,
            nickname: nickname.trim(),
            avatar_url: avatarUrl,
          },
        };

        wx.setStorageSync("userInfo", updatedUserInfo);

        wx.showToast({
          title: "信息完善成功",
          icon: "success",
        });

        // 跳转到指定页面或首页
        setTimeout(() => {
          if (this.data.returnUrl) {
            wx.redirectTo({
              url: this.data.returnUrl,
            });
          } else {
            wx.switchTab({
              url: "/pages/home/index",
            });
          }
        }, 1500);
      } else {
        throw new Error(result.message || "更新失败");
      }
    } catch (error) {
      wx.showToast({
        title: error.message || "完善信息失败",
        icon: "none",
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "甲年华美甲美睫 - 完善信息",
      desc: "完善您的个人信息，享受更好的服务体验",
      path: "/pages/completeProfile/index",
      imageUrl: "/images/share-profile.jpg",
    };
  },

  /**
   * 加载用户设置
   */
  async loadUserSettings() {
    try {
      const { settingsApi } = require("../../utils/api.js");
      const result = await settingsApi.getUserSettings();

      if (result && result.code === 0) {
        this.setData({
          userSettings: result.data,
        });
        // 更新导航栏标题
        this.updateNavigationTitle();
      }
    } catch (error) {
      console.log("用户设置API异常:", error);
    }
  },

  /**
   * 更新导航栏标题
   */
  updateNavigationTitle() {
    const { userSettings } = this.data;
    const title = userSettings.setting1 || "";
    wx.setNavigationBarTitle({
      title: title,
    });
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    const { userSettings } = this.data;
    const title = userSettings.setting1 || "";

    return {
      title: `甲年华美甲美睫 - ${title}`,
      query: "",
      imageUrl: "/images/share-profile.jpg",
    };
  },
});
